package com.example.cloud.controller.auth;

import com.example.cloud.entity.User;
import com.example.cloud.exception.AuthException;
import com.example.cloud.interceptor.AuthInterceptor;
import com.example.cloud.service.AuthService;
import com.example.cloud.service.UserService;
import com.example.cloud.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/auth")
@Tag(name = "认证接口", description = "用户认证相关接口")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserService userService;
    
    @Autowired
    private AuthService authService;

    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.secret}")
    private String appSecret;

    /**
     * 微信登录
     */
    @PostMapping("/wx-login")
    @ResponseBody
    @Operation(summary = "微信登录", description = "通过微信小程序登录")
    public Result<Map<String, Object>> wxLogin(
            @RequestBody @Parameter(description = "微信登录凭证") Map<String, String> params) {
        String code = params.get("code");
        if (code == null || code.isEmpty()) {
            logger.error("微信登录失败：登录凭证不能为空");
            return Result.error("登录凭证不能为空");
        }

        try {
            logger.info("开始微信登录，code: {}", code);

            // 调用AuthService的wxLogin方法
            Map<String, Object> data = authService.wxLogin(code);
            logger.info("微信登录成功，用户ID: {}", ((Map)data.get("userInfo")).get("id"));
            return Result.success(data);
        } catch (Exception e) {
            logger.error("微信登录失败: {}", e.getMessage(), e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/user-info")
    @Operation(summary = "更新用户信息", description = "更新用户的头像和昵称")
    public Result<Map<String, Object>> updateUserInfo(
            HttpServletRequest request,
            @RequestBody @Parameter(description = "用户信息") Map<String, Object> params) {
        // 从请求属性中获取用户ID
        Long userId = AuthInterceptor.getCurrentUserId(request);
        // 拦截器已经处理了认证，这里不需要再次检查
        
        String nickName = (String) params.get("nickName");
        String avatarUrl = (String) params.get("avatarUrl");
        
        try {
            logger.info("更新用户信息，userId: {}, nickName: {}, avatarUrl: {}", userId, nickName, avatarUrl);
            
            // 调用AuthService的updateUserInfo方法
            Map<String, Object> data = authService.updateUserInfo(userId, nickName, avatarUrl);
            return Result.success(data);
        } catch (Exception e) {
            logger.error("更新用户信息失败", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    @Operation(summary = "退出登录", description = "用户退出登录")
    public Result<Void> logout(HttpServletRequest request) {
        // 从请求属性中获取用户ID
        Long userId = AuthInterceptor.getCurrentUserId(request);
        // 拦截器已经处理了认证，这里不需要再次检查
        
        // 调用AuthService的logout方法
        authService.logout();
        return Result.success();
    }

    /**
     * 刷新令牌
     */
    @PostMapping("/refresh-token")
    @Operation(summary = "刷新令牌", description = "刷新用户的访问令牌")
    public Result<Map<String, Object>> refreshToken() {
        // 调用AuthService的refreshToken方法
        Map<String, Object> data = authService.refreshToken();
        return Result.success(data);
    }
} 